package com.studymaster.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.studymaster.controller.util.Convert;
import com.studymaster.domain.Event;
import com.studymaster.service.EventService;

@Controller  
public class EventConstroller {  
	@Autowired
	private EventService mEventService;
	
    public EventConstroller() {}  
    
	@RequestMapping(value = "/getAllEvents.do")
	public ModelAndView login(HttpServletRequest request, ModelMap model) {
		List<Event> events = mEventService.getAllEvents();
		
		model.put("events", events );
		return new ModelAndView(new MappingJacksonJsonView(), model);
	}
	
	@RequestMapping(value = "/backupEvents.do", method = RequestMethod.POST)
	public ModelAndView backupEvents(@RequestParam("events") String eventsJson
			,HttpServletRequest request, ModelMap model) {
		try {
			eventsJson = URLDecoder.decode(eventsJson, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		List<Event>  events  = Convert.getEventsByMap(eventsJson);
		
		boolean success = mEventService.saveAllEvents(events);
		
		if( success ){
			if ( events.size() == 0 ){
				model.put("resultcode", 1);
			}else{
				model.put("resultcode", 0);
			}
		}else{
			model.put("resultcode", 2);
		}
		
		return new ModelAndView(new MappingJacksonJsonView(), model);
	}
    
}  
